package com.project.service.impl;

import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl extends BaseService implements IUserService {

    @Override
    public UserBean login(String code, String psw) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.login(code,psw);
        session.close();
        return user;
    }

    @Override
    public void changePsw(int code, String newpsw) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updatePwd(code,newpsw);
        session.commit();
        session.close();
    }

    @Override
    public boolean add(UserBean user) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        if(mapper.checkName(user.getCode()) == false){
            mapper.addUser(user);
            session.commit();
            session.close();
            return true;
        }
        session.close();
        return false;
    }

    @Override
    public void del(int id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.delUser(id);
        session.commit();
        session.close();
    }

    @Override
    public UserBean findById(int id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.findById(id);
        session.close();
        return user;
    }

    @Override
    public void changeGrade(int id, String grade) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updateRank(id,grade);
        session.commit();
        session.close();
    }

    @Override
    public List<UserBean> findAll() {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<UserBean> list = mapper.findAll();
        session.close();
        return list;
    }

    public static void main(String[] args) {
        IUserService service = new UserServiceImpl();
//        System.out.println(service.login("tom", "111"));
//        service.changePsw(1,"111");
//        System.out.println(service.findById(1));
//        service.changeGrade(1,"班主任");
        System.out.println(service.add(new UserBean("tom","刘晓彤","班主任")));
//        service.del(5);
//        System.out.println(service.findAll());
    }
}
